<route lang="json5">
{
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '记账',
  },
}
</route>
<template>
  <view class="finance-record-page">
    <!-- 自定义导航栏 -->
    <view
      class="custom-nav-bar bg-white p-4 border-b border-gray-200 flex justify-between items-center"
      :style="{ paddingTop: safeAreaInsets?.top + 'px' }"
    >
      <view class="flex items-center">
        <text class="i-fa-solid:chevron-left text-lg mr-2" @click="goBack"></text>
        <text class="text-xl font-semibold">{{ isEdit ? '编辑记录' : '新增记录' }}</text>
      </view>
      <view>
        <text class="text-blue-500 font-medium" @click="saveRecord">保存</text>
      </view>
    </view>

    <!-- 表单内容 -->
    <scroll-view scroll-y class="record-container">
      <view class="p-4">
        <!-- 收支类型 -->
        <view class="type-selector">
          <view
            :class="['type-item', { active: record.type === 'expense' }]"
            @click="record.type = 'expense'"
          >
            <text>支出</text>
          </view>
          <view
            :class="['type-item', { active: record.type === 'income' }]"
            @click="record.type = 'income'"
          >
            <text>收入</text>
          </view>
        </view>

        <!-- 金额输入 -->
        <view class="amount-input-container">
          <text class="currency-symbol">¥</text>
          <input
            type="digit"
            class="amount-input"
            placeholder="0.00"
            v-model="record.amount"
            focus
          />
        </view>

        <!-- 类别选择 -->
        <view class="form-item" @click="showCategorySelector = true">
          <text class="form-label">类别</text>
          <view class="form-value flex items-center justify-between">
            <view class="flex items-center" v-if="record.category">
              <view class="category-icon">
                <text :class="getCategoryIcon(record.category)"></text>
              </view>
              <text class="ml-2">{{ record.category }}</text>
            </view>
            <text v-else class="text-gray-400">请选择类别</text>
            <text class="i-fa-solid:chevron-right text-gray-400"></text>
          </view>
        </view>

        <!-- 日期选择 -->
        <view class="form-item" @click="showDatePicker = true">
          <text class="form-label">日期</text>
          <view class="form-value flex items-center justify-between">
            <text>{{ record.date || formatDate(new Date()) }}</text>
            <text class="i-fa-solid:chevron-right text-gray-400"></text>
          </view>
        </view>

        <!-- 账户选择 -->
        <view class="form-item" @click="showAccountSelector = true">
          <text class="form-label">账户</text>
          <view class="form-value flex items-center justify-between">
            <text>{{ record.account || '现金' }}</text>
            <text class="i-fa-solid:chevron-right text-gray-400"></text>
          </view>
        </view>

        <!-- 备注 -->
        <view class="form-item stretch-item">
          <text class="form-label">备注</text>
          <input type="text" class="form-input" placeholder="添加备注..." v-model="record.note" />
        </view>

        <!-- 照片 -->
        <view class="photo-section">
          <text class="section-title">照片</text>
          <view class="photo-list">
            <view v-for="(photo, index) in record.photos" :key="index" class="photo-item">
              <image :src="photo" class="photo-image" mode="aspectFill"></image>
              <view class="photo-delete" @click="removePhoto(index)">
                <text class="i-fa-solid:times"></text>
              </view>
            </view>
            <view class="photo-add" @click="addPhoto" v-if="record.photos.length < 3">
              <text class="i-fa-solid:camera"></text>
            </view>
          </view>
        </view>

        <!-- 删除按钮 -->
        <view v-if="isEdit" class="delete-button" @click="confirmDelete">
          <text class="text-white">删除记录</text>
        </view>
      </view>
    </scroll-view>

    <!-- 类别选择器弹窗 -->
    <view v-if="showCategorySelector" class="overlay" @click="showCategorySelector = false">
      <view class="selector-popup" @click.stop>
        <view class="selector-header">
          <text class="selector-title">选择类别</text>
          <text class="selector-close" @click="showCategorySelector = false">取消</text>
        </view>
        <view class="selector-content">
          <view class="category-grid">
            <view
              v-for="(category, index) in getCategoriesByType()"
              :key="index"
              class="category-item"
              @click="selectCategory(category.name)"
            >
              <view class="category-icon-wrapper">
                <text :class="category.icon"></text>
              </view>
              <text class="category-name">{{ category.name }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 日期选择器弹窗 -->
    <view v-if="showDatePicker" class="overlay" @click="showDatePicker = false">
      <view class="selector-popup" @click.stop>
        <view class="selector-header">
          <text class="selector-title">选择日期</text>
          <text class="selector-close" @click="showDatePicker = false">取消</text>
        </view>
        <view class="selector-content">
          <picker
            mode="date"
            :value="record.date || formatDate(new Date())"
            @change="onDateChange"
            class="w-full"
          >
            <view class="picker-view">
              <text>{{ record.date || formatDate(new Date()) }}</text>
            </view>
          </picker>
        </view>
      </view>
    </view>

    <!-- 账户选择器弹窗 -->
    <view v-if="showAccountSelector" class="overlay" @click="showAccountSelector = false">
      <view class="selector-popup" @click.stop>
        <view class="selector-header">
          <text class="selector-title">选择账户</text>
          <text class="selector-close" @click="showAccountSelector = false">取消</text>
        </view>
        <view class="selector-content">
          <view
            v-for="(account, index) in accounts"
            :key="index"
            class="selector-item"
            @click="selectAccount(account)"
          >
            <text>{{ account }}</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
defineOptions({
  name: 'FinanceRecordPage',
})

// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()

// 是否为编辑模式
const isEdit = ref(false)
// 记录ID参数
const recordId = ref('')

// 弹窗状态
const showCategorySelector = ref(false)
const showDatePicker = ref(false)
const showAccountSelector = ref(false)

// 账户列表
const accounts = ref(['现金', '微信', '支付宝', '银行卡', '信用卡'])

// 支出类别
const expenseCategories = ref([
  { name: '餐饮', icon: 'i-fa-solid:utensils text-orange-500' },
  { name: '购物', icon: 'i-fa-solid:shopping-bag text-pink-500' },
  { name: '交通', icon: 'i-fa-solid:car text-blue-500' },
  { name: '住宿', icon: 'i-fa-solid:home text-teal-500' },
  { name: '娱乐', icon: 'i-fa-solid:film text-purple-500' },
  { name: '医疗', icon: 'i-fa-solid:briefcase-medical text-red-500' },
  { name: '教育', icon: 'i-fa-solid:book text-green-500' },
  { name: '通讯', icon: 'i-fa-solid:mobile-alt text-indigo-500' },
  { name: '服饰', icon: 'i-fa-solid:tshirt text-yellow-500' },
  { name: '美容', icon: 'i-fa-solid:spa text-pink-500' },
  { name: '家居', icon: 'i-fa-solid:couch text-brown-500' },
  { name: '其他', icon: 'i-fa-solid:ellipsis-h text-gray-500' },
])

// 收入类别
const incomeCategories = ref([
  { name: '工资', icon: 'i-fa-solid:money-bill-wave text-green-500' },
  { name: '奖金', icon: 'i-fa-solid:award text-yellow-500' },
  { name: '投资', icon: 'i-fa-solid:chart-line text-blue-500' },
  { name: '兼职', icon: 'i-fa-solid:laptop-code text-purple-500' },
  { name: '转账', icon: 'i-fa-solid:exchange-alt text-teal-500' },
  { name: '报销', icon: 'i-fa-solid:receipt text-orange-500' },
  { name: '其他', icon: 'i-fa-solid:ellipsis-h text-gray-500' },
])

// 记录数据
const record = ref({
  id: '',
  type: 'expense',
  amount: '',
  category: '',
  date: formatDate(new Date()),
  account: '现金',
  note: '',
  photos: [] as string[],
})

// 根据类型获取相应的类别
const getCategoriesByType = () => {
  return record.value.type === 'expense' ? expenseCategories.value : incomeCategories.value
}

// 获取类别图标
const getCategoryIcon = (categoryName: string) => {
  const categories =
    record.value.type === 'expense' ? expenseCategories.value : incomeCategories.value
  const category = categories.find((c) => c.name === categoryName)
  return category ? category.icon : 'i-fa-solid:question text-gray-500'
}

// 日期改变
const onDateChange = (e: any) => {
  record.value.date = e.detail.value
  showDatePicker.value = false
}

// 选择类别
const selectCategory = (category: string) => {
  record.value.category = category
  showCategorySelector.value = false
}

// 选择账户
const selectAccount = (account: string) => {
  record.value.account = account
  showAccountSelector.value = false
}

// 添加照片
const addPhoto = () => {
  uni.chooseImage({
    count: 1,
    success: (res) => {
      record.value.photos.push(res.tempFilePaths[0])
    },
  })
}

// 移除照片
const removePhoto = (index: number) => {
  record.value.photos.splice(index, 1)
}

// 确认删除
const confirmDelete = () => {
  uni.showModal({
    title: '确认删除',
    content: '确定要删除此记录吗？此操作无法撤销。',
    success: (res) => {
      if (res.confirm) {
        deleteRecord()
      }
    },
  })
}

// 删除记录
const deleteRecord = () => {
  // 在实际应用中，这里应该调用API删除记录
  uni.showToast({
    title: '删除成功',
    icon: 'success',
  })
  setTimeout(() => {
    goBack()
  }, 1500)
}

// 保存记录
const saveRecord = () => {
  // 验证必填字段
  if (!record.value.amount || parseFloat(record.value.amount) <= 0) {
    uni.showToast({
      title: '请输入有效金额',
      icon: 'none',
    })
    return
  }

  if (!record.value.category) {
    uni.showToast({
      title: '请选择类别',
      icon: 'none',
    })
    return
  }

  // 在实际应用中，这里应该调用API保存记录
  uni.showToast({
    title: isEdit.value ? '更新成功' : '创建成功',
    icon: 'success',
  })
  setTimeout(() => {
    goBack()
  }, 1500)
}

// 返回上一页
const goBack = () => {
  uni.navigateBack()
}

// 格式化日期
const formatDate = (date: Date) => {
  const year = date.getFullYear()
  const month = (date.getMonth() + 1).toString().padStart(2, '0')
  const day = date.getDate().toString().padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 页面加载
onLoad((options) => {
  if (options && options.id) {
    isEdit.value = true
    recordId.value = options.id

    // 在实际应用中，这里应该根据recordId从API或存储中获取记录详情
    // 这里使用模拟数据
    if (recordId.value === '1') {
      record.value = {
        id: '1',
        type: 'expense',
        amount: '128.50',
        category: '餐饮',
        date: '2023-06-20',
        account: '微信',
        note: '和朋友聚餐',
        photos: [],
      }
    }
  }
})
</script>

<style lang="scss">
.finance-record-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f2f2f7;
}

.record-container {
  flex: 1;
  width: 100%;
}

.type-selector {
  display: flex;
  margin-bottom: 16px;
  overflow: hidden;
  background-color: white;
  border-radius: 8px;
}

.type-item {
  display: flex;
  flex: 1;
  align-items: center;
  justify-content: center;
  height: 48px;
  font-size: 16px;
}

.type-item.active {
  color: white;
  background-color: #007aff;
}

.amount-input-container {
  display: flex;
  align-items: center;
  padding: 16px;
  margin-bottom: 16px;
  background-color: white;
  border-radius: 8px;
}

.currency-symbol {
  margin-right: 8px;
  font-size: 28px;
  font-weight: 500;
}

.amount-input {
  flex: 1;
  height: 48px;
  font-size: 28px;
}

.form-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  margin-bottom: 1px;
  background-color: white;
  border-radius: 8px;
}

.form-label {
  width: 80px;
  font-size: 16px;
  color: #333;
}

.form-value {
  flex: 1;
  font-size: 16px;
  color: #333;
  text-align: right;
}

.form-input {
  flex: 1;
  height: 24px;
  font-size: 16px;
  text-align: right;
}

.stretch-item {
  margin-bottom: 16px;
}

.section-title {
  margin-bottom: 16px;
  font-size: 16px;
  font-weight: 500;
}

.photo-list {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.photo-item,
.photo-add {
  position: relative;
  width: 100px;
  height: 100px;
  overflow: hidden;
  border-radius: 8px;
}

.photo-image {
  width: 100%;
  height: 100%;
}

.photo-delete {
  position: absolute;
  top: 4px;
  right: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
  color: white;
  background-color: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
}

.photo-add {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: #8e8e93;
  background-color: #e5e5ea;
}

.category-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  background-color: #f2f2f7;
  border-radius: 50%;
}

.delete-button {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 48px;
  margin-top: 40px;
  font-size: 16px;
  background-color: #ff3b30;
  border-radius: 8px;
}

.overlay {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 100;
  display: flex;
  align-items: flex-end;
  background-color: rgba(0, 0, 0, 0.4);
}

.selector-popup {
  width: 100%;
  max-height: 70vh;
  overflow: hidden;
  background-color: white;
  border-top-left-radius: 12px;
  border-top-right-radius: 12px;
}

.selector-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  border-bottom: 1px solid #e5e5ea;
}

.selector-title {
  font-size: 16px;
  font-weight: 500;
}

.selector-close {
  font-size: 16px;
  color: #007aff;
}

.selector-content {
  max-height: calc(70vh - 54px);
  padding: 16px;
  overflow-y: auto;
}

.selector-item {
  padding: 12px 0;
  border-bottom: 1px solid #e5e5ea;
}

.selector-item:last-child {
  border-bottom: none;
}

.category-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
}

.category-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.category-icon-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 48px;
  height: 48px;
  margin-bottom: 8px;
  font-size: 20px;
  background-color: #f2f2f7;
  border-radius: 50%;
}

.category-name {
  font-size: 12px;
  color: #333;
}

.picker-view {
  padding: 12px;
  text-align: center;
  background-color: #f2f2f7;
  border-radius: 8px;
}
</style>
